--*************ANIMATION SUITE****************--
--**************Property of Hxrmn*****************--
--*************Hxrmn@comcast.net*****************--
--DO NOT RE-DISTRIBUTE WITHOUT HXRMN'S CONSENT--
--********************************************--

Track = {}

function Track:Create(animator)
	local track = {}
	setmetatable(track, self)
	self.__index = self
	track.frames = {}
	track.animator = animator;
	track.time = animator.curTime
	track.armed = false
	track.id = -1
	track.valid = true
	
	return track
end

function Track:SetTrackPanel(panel)
	self.panel = panel
end

function Track:GetTrackPanel()
	return self.panel
end

function Track:SetId(id)
	self.id = id
end

function Track:GetId()
	return self.id
end

function Track:SetArmed(bool)
	self.armed = bool
end

function Track:IsArmed()
	return self.armed
end

function Track:CaptureKeyFrame()
	if(self.time > 0) then
		self.frames[self.time] = KeyFrame:Create(self.time, self)
		if(CLIENT) then AS_KeyFrameUpdated(self,self.frames[self.time]) end
	end
end

function Track:GetLength()
	--Enables tweening capabillity
	local Max = 0;
	for _,frame in pairs(self.frames) do
		local t = frame:GetTime()
		if(t > Max) then
			Max = t;
		end
	end
	return Max
end

function Track:SetTime(t)
	self.time = t;
	self:ApplyKeyFrame()
end

function Track:ApplyKeyFrame()
	local frame = self.frames[self.time]
	if(frame != nil) then
		frame:Apply();
	end
end

function Track:SetEntity(ent)
	if(IsAnimatable(ent)) then
		self.entity = ent
		return true
	end
	return false
end

function Track:GetEntity()
	if(self.entity != nil and self.entity:IsValid()) then
		return self.entity
	else
		if(self.valid == true) then
			self.animator:RemoveTrackById(self:GetId())
			self:Destroy()
		end
	end
end

function Track:Clear()
	if(self.frames != nil) then
		for k,v in pairs(self.frames) do
			if(v != nil) then v:Clear(); end
		end
		self.frames = {}
	end
end

function Track:GetPhysicsObjects()
	local objects = {}
	if(self.entity != nil and self.entity:IsValid()) then
		local pcount = self.entity:GetPhysicsObjectCount()
		if(pcount > 1) then
			for i=0, pcount-1 do
				local phys = self.entity:GetPhysicsObjectNum(i)
				if(phys:IsValid()) then
					table.insert(objects,phys)
				end
			end
		else
			local phys = self.entity:GetPhysicsObject()
			if(phys != nil and phys:IsValid()) then
				table.insert(objects,phys)
			end	
		end
	end
	return objects
end

function Track:Destroy()
	self.valid = false
	self:Clear()
	if(self:GetEntity() != nil and self:GetEntity():IsValid()) then
		self:GetEntity().hasTrack = false
		for k,v in pairs(self:GetPhysicsObjects()) do
			if(v != nil and v:IsValid()) then
				v:EnableMotion(true)
				v:EnableGravity(true)
				v:Wake()
			end
		end
	end
	self.entity = nil
end